package vn.demand.dragon.view
{
	import flash.events.ContextMenuEvent;
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	
	import flexed.widgets.alerts.alert;
	
	import mx.controls.Alert;
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.controls.dataGridClasses.DataGridItemRenderer;
	import mx.events.CloseEvent;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.model.ProjectFilesProxy;
	import vn.demand.dragon.model.UserProxy;
	import vn.demand.dragon.view.components.ProjectFilesScreen;
	import vn.demand.utils.DpUtils;

	public class ProjectFilesScreenMediator extends Mediator
	{
		public static const NAME:String = "ProjectFilesScreenMediator";
		
		private var masterdataProxy:MasterdataProxy;
		private var pfileProxy:ProjectFilesProxy;
		private var userProxy:UserProxy;
		
		private var projectVO:Object;
		private var fRef:FileReference = new FileReference();
		
		public static function makeId(projectVO:Object):String {
        	return NAME + projectVO.project_id + "::";
        }
		
		public function ProjectFilesScreenMediator(projectVO:Object, mediatorName:String, viewComponent:Object)
		{
			super(mediatorName, viewComponent);
			
			this.projectVO = projectVO;
			
			masterdataProxy = facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
			pfileProxy = facade.retrieveProxy(ProjectFilesProxy.makeId(projectVO)) as ProjectFilesProxy;
			userProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
			
			projectFilesScreen.addEventListener(ProjectFilesScreen.PROJECT_FILES_SCREEN_UI_CREATED, prepareData);
		}
		
		public function prepareData(event:Event):void {
			for each (var col:DataGridColumn in gridProjectFiles.columns) {
				switch (col.dataField) {
					default:
						break;
				}
			}
			
			projectFilesScreen.addEventListener(ProjectFilesScreen.NEW_FILE, onNewFile);
			projectFilesScreen.addEventListener(ProjectFilesScreen.REFRESH_FILES_LIST, onReloadProjectFiles);
			projectFilesScreen.addEventListener(ProjectFilesScreen.REMOVE_FILE, onRemoveProjectFiles);
			projectFilesScreen.addEventListener(ProjectFilesScreen.CLOSE_FILES_LIST, onCloseProjectFiles);
			projectFilesScreen.addEventListener(ProjectFilesScreen.OPEN_FILE, onOpenFile);
			
			createContextMenu();
			
			gridProjectFiles.contextMenu = m;
			
			doLoadProjectFiles();
			
			projectFilesScreen.canEdit = true;
			if (!DpUtils.isTrue(userProxy.userInfo.project_edit) || masterdataProxy.isProjectCompleted(this.projectVO)) {
				projectFilesScreen.canEdit = false;
				removeMenu.enabled = false;
			}
		}
		
		public function onRemoveProjectFiles(event:Event):void {
			doRemoveProjectFiles(gridProjectFiles.selectedIndex);
		}
		
		public function onBrowseReference(event:Event):void {
			sendNotification(FFIAApplicationFacade.BROWSE_REFERENCE_LIST);
		}
		
		public function onNewFile(event:Event):void {
			sendNotification(FFIAApplicationFacade.ADD_NEW_PROJECT_FILE, {'projectVO': projectVO, 'file': null});
		}
		
		public function onOpenFile(event:Event):void {
			var pfileId:int = projectFilesScreen.gridFiles.selectedItem.pfile_id;
			navigateToURL(new URLRequest('http://dev.dragon.com/index.php?m=projects&a=do_file_crud&project_id=' 
			+ projectVO.project_id+ '&cmd=get&suppressHeaders=1&pfile_id=' + pfileId));
		}
		
		private function onCloseProjectFiles(event:Event):void {
        	sendNotification(FFIAApplicationFacade.CLOSE_PROJECT_PANEL, null, ProjectPanelMediator.makeId(projectVO));
        }
		
		var m:ContextMenu;
		var copyMenu:ContextMenuItem;
        var pasteMenu:ContextMenuItem;
        var removeMenu:ContextMenuItem;
        
        private function createContextMenu():void {
		    m = new ContextMenu();
		    m.hideBuiltInItems();
		    var customItemsArr:Array = new Array();
		    copyMenu = new ContextMenuItem("Copy Row");
		    pasteMenu = new ContextMenuItem("Patse Row");
		    removeMenu = new ContextMenuItem("Remove Row");
		    
		    copyMenu.addEventListener("menuItemSelect", copyHandler);
		    pasteMenu.addEventListener("menuItemSelect", pasteHandler);
		    removeMenu.addEventListener("menuItemSelect", removeHandler);
		    
		    pasteMenu.enabled = false;
		    
		    customItemsArr.push(copyMenu);
		    customItemsArr.push(pasteMenu);
		    customItemsArr.push(removeMenu);
		    
		    m.customItems = customItemsArr;
	    }
	    
	    private var copyItem:Object = null;
	    
	    private function copyHandler(e:ContextMenuEvent):void
	    {
	    	var itemIndex:Number = -1;
	    	if (e.mouseTarget is DataGridItemRenderer) {
		    	itemIndex = DataGridItemRenderer(e.mouseTarget).listData.rowIndex;
	    	} else {
	    		itemIndex = gridProjectFiles.selectedIndex;
	    	}
	    	if (itemIndex < 0) return;
	    	pasteMenu.enabled = true;	    	
		    copyItem = gridProjectFiles.dataProvider.getItemAt(itemIndex);
	    }
	    
	    private function pasteHandler(e:ContextMenuEvent):void
	    {
	    	if (masterdataProxy.isProjectCompleted(this.projectVO)) {
	    		return;
			}
		    var itemIndex:Number = -1;
	    	if (e.mouseTarget is DataGridItemRenderer) {
		    	itemIndex = DataGridItemRenderer(e.mouseTarget).listData.rowIndex;
	    	} else {
	    		itemIndex = gridProjectFiles.selectedIndex;
	    	}
	    	if (itemIndex < 0) return;
	    	pfileProxy.copyProjectFiles(projectVO, copyItem, itemIndex);
	    }
	    
	    private function removeHandler(e:ContextMenuEvent):void
	    {
	    	if (masterdataProxy.isProjectCompleted(this.projectVO)) {
	    		return;
			}
	    	var itemIndex:Number = -1;
	    	if (e.mouseTarget is DataGridItemRenderer) {
		    	itemIndex = DataGridItemRenderer(e.mouseTarget).listData.rowIndex;
	    	} else {
	    		itemIndex = gridProjectFiles.selectedIndex;
	    	}
	    	if (itemIndex < 0) {
	    		alert.error("You don't select any row to remove!");
	    		return;
	    	}
		    doRemoveProjectFiles(itemIndex);
	    }
		
		
		function onReloadProjectFiles(event:Event):void {
        	doLoadProjectFiles();
		}
		
		public function get projectFilesScreen():ProjectFilesScreen
		{
            return viewComponent as ProjectFilesScreen;
        }
        
        public function get gridProjectFiles():DataGrid {
			return projectFilesScreen.gridFiles;
		}
		
		/**
         * List all notifications this Mediator is interested in.
         * <P>
         * Automatically called by the framework when the mediator
         * is registered with the view.</P>
         * 
         * @return Array the list of Nofitication names
         */
        override public function listNotificationInterests():Array 
        {
            return [ 
            	FFIAApplicationFacade.REFERENCE_SELECTED,
            	FFIAApplicationFacade.LOAD_PFILES_BY_REFERENCE_FAILED,
            	FFIAApplicationFacade.LOAD_PFILES_BY_REFERENCE_SUCCESS,
            	FFIAApplicationFacade.PROJECT_FILE_UPDATED,
            	FFIAApplicationFacade.RELOAD_PFILES
			];
        }
        
        /**
         * Handle all notifications this Mediator is interested in.
         * <P>
         * Called by the framework when a notification is sent that
         * this mediator expressed an interest in when registered
         * (see <code>listNotificationInterests</code>.</P>
         * 
         * @param INotification a notification 
         */
        override public function handleNotification( note:INotification ):void 
        {
        	RIALogger.debug(this, "handleNotification: " + Number(projectVO.project_id));
        	if (Number(note.getType()) != Number(projectVO.project_id)) {
        		return;
        	}
            switch ( note.getName() ) 
			{
				case FFIAApplicationFacade.LOAD_PFILES_BY_REFERENCE_SUCCESS:
                	gridProjectFiles.dataProvider = pfileProxy.pfilesDP;
                	gridProjectFiles.errorString = null;
                	break;
				case FFIAApplicationFacade.LOAD_PFILES_BY_REFERENCE_FAILED:
                	gridProjectFiles.errorString = note.getBody().toString();
                	break;
				case FFIAApplicationFacade.PROJECT_FILE_UPDATED:
					alert.info("Reference lines updated");
					pfileProxy.pfilesDP.addItem(pfileProxy.newProjectFiles());
					gridProjectFiles.errorString = null;
					break;
				case FFIAApplicationFacade.PROJECT_FILE_UPDATE_FAILED:
					alert.error(note.getBody() as String);
					break;
				case FFIAApplicationFacade.RELOAD_PFILES:
					doLoadProjectFiles();
					break;
            }
        }
        	
        public function doLoadProjectFiles():void {
			pfileProxy.loadProjectFilesByReference();
		}
        			
        public function doRemoveProjectFiles(selIndex:int):void {
        	if (selIndex < 0 || selIndex >= gridProjectFiles.dataProvider.length) {
        		alert.error("You should select a row to remove");
        		return;
        	}
        	alert.confirm("Do you want to remove row at [" + (selIndex + 1) + "]?", function(e:CloseEvent) {
        		if (e.detail != Alert.YES) {
        			return;
        		}
        		RIALogger.debug(this, "Remove row at " + selIndex);
        		pfileProxy.removeProjectFiles(selIndex);
        		gridProjectFiles.selectedIndex = -1;
        	});
        }
	}	
}